<template>
	<div class="search clear">
		<div class="search-box-layout">
			<Row :gutter="24">
				<div v-for="(item, index) in columns" :key="index">
					<Col :span="item.span || span">
						<p class="label">{{ item.title }}</p>
						<div class="ipt">
							<Select
								v-model="searchParams[item.key]"
								v-if="item.type == 'select'"
								filterable
								:placeholder="item.placeholder || '请选择'"
								:clearable="typeof item.clearable == 'boolean' ? item.clearable : true"
								@on-change="selectChange($event, item.key)"
								:multiple="!!item.multiple"
								:max-tag-count="item.maxTagCount || 2"
							>
								<Option
									v-for="(itemS, indexS) of item.dicData ? item.dicData : allDicData[item.key + 'List']"
									:value="itemS[!!item.params ? item.params.value : 'value']"
									:key="indexS"
									:label="itemS[!!item.params ? item.params.label : 'label']"
								>
								</Option>
							</Select>
							<Select
								v-model="searchParams[item.key]"
								v-else-if="item.type == 'search'"
								filterable
								:clearable="typeof item.clearable == 'boolean' ? item.clearable : true"
								@on-change="selectChange($event, item.key)"
								:remote-method="fn['get' + item.key]"
								:placeholder="item.placeholder || '请选择'"
							>
								<Option
									v-for="(itemS, indexS) of item.dicData ? item.dicData : allDicData[item.key + 'List']"
									:value="itemS[!!item.params ? item.params.value : 'value']"
									:key="indexS"
									:label="itemS[!!item.params ? item.params.label : 'label']"
								>
								</Option>
							</Select>

							<Cascader
								v-else-if="item.type == 'cascader'"
								:data="item.dicData ? item.dicData : allDicData[item.key + 'List']"
								v-model="searchParams[item.key]"
								change-on-select
								:clearable="!!item.clearable"
								:placeholder="item.placeholder || '请选择'"
							>
							</Cascader>

							<!-- 	:options="timeOptions[`${item.key}EndOption`]"
								:time-picker-options="{ disabledHours: disabledHours, disabledMinutes: disabledMinutes, disabledSeconds: disabledSeconds }" -->
							<DatePicker
								v-else-if="
									item.type == 'date' || item.type == 'daterange' || item.type == 'month' || item.type == 'datetimerange' || item.type == 'year'
								"
								:value="searchParams[item.key]"
								@on-change="timeChange($event, item.key)"
								:type="item.type"
								:clearable="typeof item.clearable == 'boolean' ? item.clearable : true"
								:format="item.format ? item.format : 'yyyy-MM-dd'"
								:placeholder="item.placeholder || '请选择日期'"
							/>

							<RadioGroup v-model="searchParams[item.key]" v-else-if="item.type == 'radio'">
								<Radio label="">{{ $t('common.all') }}</Radio>
								<Radio label="1">{{ $t('common.Yes') }}</Radio>
								<Radio label="0">{{ $t('common.No') }}</Radio>
							</RadioGroup>

							<Input
								v-else
								type="text"
								clearable
								v-model="searchParams[item.key]"
								:placeholder="item.placeholder || '请输入'"
								class="inputBorder"
								:maxlength="32"
							></Input>
						</div>
					</Col>
				</div>
				<div>
					<Col :span="otherSpan || 4">
						<div>
							<p class="label hide-label">--</p>
							<div class="ipt">
								<Button type="primary" class="search-btn" @click="getSearch()">{{ $t('common.Query') }} </Button>
								<Button class="reset-btn" @click="reset()">{{ $t('common.reset') }} </Button>
								<slot name="others"></slot>
							</div>
						</div>
					</Col>
				</div>
			</Row>
		</div>
	</div>
</template>

<script>
import recursion from '@/util/recursion';
import toggleTableOperation from '@/mixins/toggleTableOperation';
export default {
	name: 'equipmentsLedgerPageList',
	mixins: [toggleTableOperation],
	props: {
		columns: {
			type: Array,
		},
		span: {
			type: Number,
			default: 4,
		},
		otherSpan: {
			type: Number,
			default: 4,
		},
	},
	data() {
		return {
			// disabledHours: [], // 审批不可选择时
			// disabledMinutes: [], // 审批不可选择分
			// disabledSeconds: [], // 审批不可选择秒
			// timeOptions: {},

			searchParams: {},
			cascaderParams: {},
			fn: {},
			allDicData: {},
			validateWritefunction: {
				deviceNo: [
					{
						required: true,
						message: this.$t('equipLedger.inputDeviceNo'),
						trigger: 'change',
					},
				],
			},
		};
	},
	created() {
		this.columns.forEach((res, index) => {
			const item = res;

			if (item.dicUrl) {
				this[item.key] = [];
				if (item.type == 'select') {
					this.getDicData(item.dicUrl, item.key);
				} else if (item.type == 'cascader') {
					this.getCasDicData(item.dicUrl, item.key, item.params);
				}
			}
			if (item.type == 'search') {
				const that = this;
				this.fn['get' + item.key] = function (query) {
					let params,
						data = {};
					if (item.queryMethod == 'post') {
						data = {
							...item.queryParams,
						};
						data[item.queryName] = query;
					} else {
						params = {
							...item.queryParams,
						};
						params[item.queryName] = query;
					}
					that
						.axios({
							method: item.queryMethod || 'get',
							url: item.dicUrl,
							params,
							data,
						})
						.then((re) => {
							if (re.code === 200) {
								const resStr = that.getData(item.resultParams, re) || [];
								that.$set(that.allDicData, `${item.key}List`, item.resultParams ? resStr : re.data);
							}
						});
				};
			}
			this.initDefaultTimeParams(item);
		});
	},
	methods: {
		initDefaultTimeParams(item) {
			if (item.type == 'date' || item.type == 'daterange' || item.type == 'month' || item.type == 'datetimerange' || item.type == 'year') {
				if (item.defaultTimeRange) {
					const valueFormatter = item.format ? item.format.replace(/y/g, 'Y').replace(/d/g, 'D') : 'YYYY-MM-DD';
					const defaultTimeRangeList = [
						this.$moment(new Date()).subtract(item.defaultTimeRange, 'days').format(valueFormatter),
						this.$moment(new Date()).format(valueFormatter),
					];

					// this.$set(this.columns[index], 'defaultTimeRangeList', defaultTimeRangeList);
					// this.$set(this.timeOptions, `${item.key}EndOption`, {
					// 	disabledDate(date) {
					// 		console.log(date);
					// 		return date && (date.valueOf() > Date.now()) || (date.valueOf()-item.defaultTimeRange*24*60*60*1000) < Date.now(); // 不能选今天之后的日期
					// 	},
					// });
					this.$set(this.searchParams, item.key, defaultTimeRangeList);
				}
			}
		},
		timeChange(val, key) {
			console.log(val instanceof Array);
			if (Array.isArray(val) && !val[0]) {
				this.$set(this.searchParams, key, null);
			} else this.$set(this.searchParams, key, val);

			const arg = this.columns.find((item) => item.key == key);
			if (arg && arg.cascader) {
				const obj = JSON.stringify({ eqfaeqr: val }).replace('eqfaeqr', `${key}`);
				this.$set(this.cascaderParams, `${arg.cascader}CascaderParams`, JSON.parse(obj));
				const arg1 = this.columns.find((item) => item.key == arg.cascader);
				this.getDicData(arg1.dicUrl, arg1.key);
			}
		},
		selectChange(val, key) {
			this.$set(this.searchParams, key, val);
		},
		getData(str, apiData) {
			const resultArray = str.split('.');
			let res = JSON.parse(JSON.stringify(apiData));
			resultArray.forEach((item, index) => {
				if (index !== 0 && item !== 'res') {
					res = res[item];
				}
			});
			return res;
		},
		getDicData(url, key) {
			this.$nextTick(() => {
				this.axios({
					method: 'get',
					url: url,
					params: {
						...this.cascaderParams[`${key}CascaderParams`],
					},
				}).then((res) => {
					this.$set(this.allDicData, `${key}List`, res.data);
				});
			});
		},

		getCasDicData(url, key, params) {
			this.$nextTick(() => {
				this.axios({
					method: 'get',
					url: url,
				}).then((res) => {
					let obj = {};
					if (params) {
						obj = params;
					} else {
						obj = {
							label: 'name',
							value: 'code',
							children: 'children',
						};
					}

					this.$set(this.allDicData, `${key}List`, recursion.convertTree(res.data, obj));
				});
			});
		},

		reset() {
			let obj = { ...this.searchParams };
			this.columns.forEach((item) => {
				if (item.noreset == true) {
					this.initDefaultTimeParams(item);
				} else delete obj[item.key];
			});
			this.$set(this, 'searchParams', obj);
			this.$emit('reset');
			this.getSearch();
		},
		//分页
		getSearch() {
			this.$emit('getSearch', this.searchParams);
		},
	},
};
</script>
